﻿using LedProject.Logger;
using Microsoft.Win32;
using Rubyer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;
using Test;
using System.Drawing;
using OpenCvSharp;
using OpenCvSharp.Extensions;

namespace LedProject
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Rubyer.RubyerWindow
    {


        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += MainWindow_Loaded;
            this.Activated += MainWindow_Activated;
        }

        //窗口控件事件加载完成
        private void MainWindow_Activated(object sender, EventArgs e)
        {
            BtConnect_Click(null, null);
        }

        //窗口加载完成
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ThemeManager.SwitchThemeMode(Rubyer.Enums.ThemeMode.Dark);
            //连接事件绑定
            btConnect.Click += BtConnect_Click;
            //手动控制亮度事件绑定
            slider.ValueChanged += Slider_ValueChanged;
            //亮度渐开事件绑定
            btSlideOpen.Click += BtSlideOpen_Click;
            //关灯事件绑定
            btClose.Click += BtClose_Click;
            //测试导入图片功能
            btTestYoloPose.Click += BtTestYoloPose_Click;
            //添加视频测试
            btStartDetect.Click += BtStartDetect_Click;
            //添加日志输出
            Log.MessageEvent += Log_MessageEvent;
        }

        //LED 当前的控制状态
        internal bool LedControlState = false;
        //是否在运行视频
        private bool IsVideo = false;
        //视频测试yolo 检测
        private void BtStartDetect_Click(object sender, RoutedEventArgs e)
        {
            if(!IsVideo)
            {
                IsVideo = true;
                Task.Run(() => {
                    try
                    {
                        // 创建视频捕获对象并打开默认摄像头（0）
                        using (var capture = new VideoCapture(0))
                        {
                            if (!capture.IsOpened())
                            {
                                Log.Info("好像没有找到摄像头哦");
                                return;
                            }

                            while (true)
                            {
                                if (!IsVideo)
                                {
                                    this.Dispatcher.Invoke(() =>
                                    {
                                        btStartDetect.Content = "开启视频检测";
                                    });
                                    break;
                                }
                                this.Dispatcher.Invoke(() =>
                                {
                                    btStartDetect.Content = "运行中(再次点击停止)";
                                });

                                Mat frame = new Mat();

                                // 从摄像头中读取当前帧图像
                                bool success = capture.Read(frame);

                                if (!success || frame.Empty())
                                    continue;

                                // 在这里进行处理或显示图像
                                var bitmap = BitmapConverter.ToBitmap(frame);
                                var result =YoloV8PoseOutput.GetPredictions(bitmap, out Bitmap outImage);
                                this.Dispatcher.Invoke(() =>
                                {
                                    ImageS.Source = PicUtil.ToBitmapSource(outImage);
                                });

                                if(result.Count>0)
                                {
                                    var one =result.FirstOrDefault();
                                    if (one.Keypoints[9].Y < one.Keypoints[0].Y&&!LedControlState)
                                    {
                                        LedControlState = true;
                                        App.Core.LedOpenOrCloseFunc(true);
                                    }
                                    if (one.Keypoints[10].Y< one.Keypoints[0].Y && LedControlState)
                                    {
                                        LedControlState = false;
                                        App.Core.LedOpenOrCloseFunc(false);
                                    }
                                }

                                Thread.Sleep(50);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        this.Dispatcher.Invoke(() =>
                        {
                            btStartDetect.Content = "开启视频检测";
                        });
                    }
                    

                });
            }
            else
            {
                IsVideo = false;
                this.Dispatcher.Invoke(() => {
                    btStartDetect.Content = "开启视频检测";
                });
            }
            
        }

        //测试导入图片功能
        private void BtTestYoloPose_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "文本文件|*.*|C#文件|*.jpg|所有文件|*.*";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == true)
            {
                Task.Run(() =>
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        ImageS.Source = null;
                    });

                    var bitmap = new Bitmap(openFileDialog.FileName);

                    YoloV8PoseOutput.GetPredictions(bitmap, out Bitmap outImage);

                    this.Dispatcher.Invoke(() =>
                    {
                        ImageS.Source = PicUtil.ToBitmapSource(outImage);
                    });

            });


        }
        }

        //滑动条改变改变光照强度
        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            var val = (int)slider.Value;
            Log.Info($"滑动亮度_{val}");
            foreach (var led in App.Core.ledDevices)
            {
                led.OpenLight(val);
            }
        }


        //连接所有Led
        private void BtConnect_Click(object sender, RoutedEventArgs e)
        {
            App.Core.InitLedDevice();
        }

        //关灯
        private void BtClose_Click(object sender, RoutedEventArgs e)
        {
            App.Core.LedOpenOrCloseFunc(false);
        }
        //灯光渐开
        private void BtSlideOpen_Click(object sender, RoutedEventArgs e)
        {
            App.Core.LedOpenOrCloseFunc(true);
        }

        //打印日志
        int richTextLine = 0;
        private void Log_MessageEvent(string text)
        {
            var str = $"{DateTime.Now.ToString("HH:mm:ss")}:{text}\n";
            this.Dispatcher.Invoke(() =>
            {
                tbLog.AppendText(str);
                tbLog.ScrollToEnd();
                if (richTextLine >= 3000)
                {
                    tbLog.Text = string.Empty;
                    richTextLine = 0;
                }
                richTextLine++;
            });
        }



        

    }
}
